window.onload = ()=>{
    var ul = document.querySelector('.operation');
    var addLi = ul.firstElementChild || ul.firstChild;
    EventListener.addEvent(addLi, 'click', (e)=>window.location.href="/officalWebsite/admin/addGroup.html");
    // 批量删除
	var delsBtn = ul.children[2];
	EventListener.addEvent(delsBtn, 'click', function(){
		var ids = getCheckedBox();
		if(ids.length>0){
			var bool = confirm('是否确认删除已选中的数据?');
			if(bool){
				ajax({
					method : 'POST',
					url : '/officalWebsite/info/group?method=removeGroups',
					async : true,
					data : {
						'ids' : ids
					},
					success : function(data){
						if(data==="true"){
							alert('删除成功！');
							searchGroups(1);
						}else{
							alert('删除失败，请重试！');
						}
					}
				});
			}
		}else{
			alert('请选择要删除的数据！');
		}
	});
    // 分页查询
    (function(){
    	// 查询条件提交
        var searchBtn = document.querySelector('#search');
        searchBtn.addEventListener('click', function() {
        	var currentPage = document.querySelector('#current').innerHTML;
        	searchGroups(currentPage);
        });
        // 首页
        var firstBtn = document.querySelector('#first');
        firstBtn.addEventListener('click', function() {
        	var currentPage = document.querySelector('#current').innerHTML;
        	currentPage = parseInt(currentPage)
        	if(currentPage==1){
        		return;
        	}else{
        		searchGroups(1);
        	}
        });
        // 尾页
        var lastBtn = document.querySelector('#last');
        lastBtn.addEventListener('click', function() {
        	var currentPage = document.querySelector('#current').innerHTML;
        	currentPage = parseInt(currentPage)
        	var totalPage = document.querySelector('#total').innerHTML;
        	if(currentPage==totalPage){
        		return;
        	}else{
        		searchGroups(totalPage);
        	}
        });
        // 上一页
        var preBtn = document.querySelector('#pre');
        preBtn.addEventListener('click', function(){
        	var currentPage = document.querySelector('#current').innerHTML;
        	currentPage = parseInt(currentPage)-1;
        	if(currentPage<=0){
        		alert('当前已是首页了！')
        	}else{
        		searchGroups(currentPage);
        	}
        });
        // 下一页
        var nextBtn = document.querySelector('#next');
        nextBtn.addEventListener('click', function(){
        	var currentPage = document.querySelector('#current').innerHTML;
        	var totalPage = document.querySelector('#total').innerHTML;
        	currentPage = parseInt(currentPage)+1;
        	if(currentPage>totalPage){
        		alert('当前已是最后一页了！')
        	}else{
        		searchGroups(currentPage);
        	}
        });
        // 指定页数跳转
        var goPageBtn = document.querySelector('#goPage');
        goPageBtn.addEventListener('click', function(){
        	var totalPage = document.querySelector('#total').innerHTML;
        	var pageValue = document.querySelector('#page').value;
        	if(pageValue<0 || pageValue>totalPage){
        		alert('请指定正确的页数！');
        	}else{
        		searchGroups(pageValue);
        	}
        });
        // 初始化调用
        searchGroups(1);
    })();
    
    function bindDynamicBtn(){
    	// 删除
        var allBtn = document.querySelectorAll('.deleteBtn');
        for(var i=0;i<allBtn.length;i++){
        	allBtn[i].addEventListener('click', function(e){
            	var bool = confirm('请确认是否删除！');
            	if(bool){
                	var tr = this.parentNode.parentNode;
                	var input = tr.children[1].lastElementChild || tr.children[1].lastChild;
                	ajax({
                		method : 'POST',
                		url : '/officalWebsite/info/group?method=removeGroup'+'&nowtime='+new Date().getTime(),
                		async : true,
                		data : {
                			'groupId' : input.value
                		},
                		success : function(data){
                			if(data){
                				alert('删除成功！');
                				searchGroups(1);	// 刷新
                			}else{
                				alert('删除失败！');
                			}
                		}
                	});
            	}
            });
        }
    }
    
    function searchGroups(currentPage){
    	var tbody = document.querySelector('#info');
    	var groupName = document.querySelector('#groupName').value;
    	var current = document.querySelector('#current');
    	var total = document.querySelector('#total');
    	var count = document.querySelector('#count');
    	// 移除原有子节点
		clearChilds();
		// 调用异步请求方法
		ajax({
	        method : 'POST',
	        url : '/officalWebsite/info/group?method=fySearchGroups'+'&nowtime='+new Date().getTime(),
	        async : true,
	        data :
	        {
	        	'groupName': groupName,
	        	'currentPage': currentPage
	        },
	        success : function(data){
	        	if(data!=="" && data!=null){
	        		data = JSON.parse(data);
		        	var groups = data.groups;
		        	for(var i=0;i<groups.length;i++){
		        		var number = (data.currentPage-1)*data.pageSize+i+1;
		        		tbody.innerHTML += '<tr>'+
		        			'<td><input type="checkbox"/></td>'+
		        			'<td>'+number+'<input type="hidden" value="'+groups[i].groupId+'" name="groupId" /></td>'+
		        			'<td>'+groups[i].groupName+'</td>'+
		        			'<td>'+groups[i].groupIntroduction+'</td>'+
		        			'<td>'+groups[i].groupImgPath+'</td>'+
		        			'<td>'+
		        				'<a href="#" target="_blank">修改</a>'+
		        				'<a href="javascript:;" class="deleteBtn">删除</a>'+
		        			'</td>'+
		        			'</tr>';
		        	}
		        	current.innerHTML = data.currentPage;
		        	total.innerHTML = data.totalPage;
		        	count.innerHTML = data.count;
		        	bindDynamicBtn();		// 为动态添加的按钮绑定事件
		        	bindSelectAll();
	        	}
	        },
	    });
    }
    
    function bindSelectAll(){
    	var boxs = document.querySelectorAll('input[type="checkbox"]');
    	var selectAll = boxs[0];
    	EventListener.addEvent(selectAll, 'click', function() {
    	    var bool = selectAll.checked;
    	    if (bool) {
    	        for (var i = 1; i < boxs.length; i++) {
    	            boxs[i].checked = bool;
    	        }
    	    } else {
    	        for (var i = 1; i < boxs.length; i++) {
    	            boxs[i].checked = bool;
    	        }    
    	    }
    	});
    }
    
    // 移除tbody的所用子节点
	function clearChilds(){
		var tbody = document.querySelector('#info');
		var trs = tbody.children;	
		// 因HTMLCollection会随着文档的改变而改变，要使用原来的可先将其保存到数组中
		var arr = [];
		for(var i=0;i<trs.length;i++){
			arr.push(trs[i]);
		}
		for(var i=0;i<arr.length;i++){
			tbody.removeChild(arr[i]);
		}
	}
	
    // 封装ajax
    function ajax(obj){
        obj = obj || {};
        obj.method = obj.method.toUpperCase() || 'POST';    // 请求方式
        obj.url = obj.url || '';    // 请求路径
        obj.async = obj.async || true;  // 是否异步
        obj.data = obj.data || null;    // 发送的数据
        obj.success = obj.success || function(){};  // 响应成功的回调函数
        obj.error = obj.error || function(){alert('服务器繁忙！')};
        if(XMLHttpRequest){
            xhr = new XMLHttpRequest();
        }else{
            xhr = new ActiveXObject('Microsoft.XMLHTTP');
        }
        var params = [];
        for(var key in obj.data){
            params.push(key+'='+obj.data[key]);
        }
        var postData = params.join('&');
        if(obj.method.toUpperCase()==='POST'){
            xhr.open(obj.method, obj.url, obj.async);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');
            xhr.send(postData);
        }else if(obj.method.toUpperCase()==='GET'){
            xhr.open(obj.method, obj.url+'&'+postData, obj.async);
            xhr.send(null);
        }
        xhr.onreadystatechange = function(){
            if(xhr.readyState==4 && xhr.status==200){
                obj.success(xhr.responseText);
            }
        }
    }
}